<template>
  <div>
    <input type="text" v-model="alt" placeholder="alt">
    <input type="text" v-model="link" placeholder="link">
    <input type="file" ref="file" @change="getFileInfo">
    <img :src="img" ref="img" alt="">
    <button @click="uploadBanner">上传</button>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  data () {
    return {
      img: '',
      alt: '',
      link: ''
    }
  },
  methods: {
    ...mapActions({
      addBannerListAction: 'banner/addBannerListAction'
    }),
    getFileInfo () {
      // 获取文件信息使用 dom.files  [{}, {}]
      const file = this.$refs.file.files[0]
      // 使用 H5新增的 api  FileReader
      const reader = new FileReader()
      reader.readAsDataURL(file) // 将文件转换为base64
      const _this = this
      reader.onload = function () { // 一定要注意this指向
        // this 指向 reader的对象
        // this.result 就是转换为base64的地址
        _this.img = this.result
      }
    },
    uploadBanner () {
      this.addBannerListAction({
        alt: this.alt,
        link: this.link,
        img: this.img
      }).then(() => {
        this.$router.push('/banner/list')
      })
    }
  }

}
</script>
